import { api } from './api'
import type { ApiResponse, PaginatedResponse, PaginationParams } from '../types'
import { Tag } from '../../types/article'

interface CreateTagRequest {
  name: string
  description?: string
}

interface UpdateTagRequest {
  name?: string
  description?: string
}

export const tagsApi = api.injectEndpoints({
  endpoints: (builder) => ({
    getTags: builder.query<ApiResponse<Tag[]>, void>({
      query: () => '/tags',
      providesTags: (result) =>
        result
          ? [
              ...result.data.map(({ id }) => ({ type: 'Tag' as const, id })),
              { type: 'Tag' as const, id: 'LIST' }
            ]
          : [{ type: 'Tag' as const, id: 'LIST' }]
    }),

    getAllTags: builder.query<ApiResponse<Tag[]>, void>({
      query: () => '/tags/all',
      providesTags: [{ type: 'Tag', id: 'LIST' }],
    }),

    getTag: builder.query<ApiResponse<Tag>, number>({
      query: (id) => `/tags/${id}`,
      providesTags: (_, __, id) => [{ type: 'Tag' as const, id }]
    }),

    createTag: builder.mutation<ApiResponse<Tag>, Pick<Tag, 'name'>>({
      query: (data) => ({
        url: '/tags',
        method: 'POST',
        body: data
      }),
      invalidatesTags: [{ type: 'Tag', id: 'LIST' }]
    }),

    updateTag: builder.mutation<
      ApiResponse<Tag>,
      Partial<Tag> & Pick<Tag, 'id'>
    >({
      query: ({ id, ...data }) => ({
        url: `/tags/${id}`,
        method: 'PUT',
        body: data
      }),
      invalidatesTags: (_, __, { id }) => [
        { type: 'Tag', id },
        { type: 'Tag', id: 'LIST' }
      ]
    }),

    deleteTag: builder.mutation<void, number>({
      query: (id) => ({
        url: `/tags/${id}`,
        method: 'DELETE'
      }),
      invalidatesTags: (_, __, id) => [
        { type: 'Tag', id },
        { type: 'Tag', id: 'LIST' }
      ]
    }),

    getPopularTags: builder.query<ApiResponse<Tag[]>, number>({
      query: (limit = 10) => ({
        url: '/tags/popular',
        params: { limit },
      }),
      providesTags: [{ type: 'Tag', id: 'POPULAR' }],
    }),
  }),
})

export const {
  useGetTagsQuery,
  useGetAllTagsQuery,
  useGetTagQuery,
  useCreateTagMutation,
  useUpdateTagMutation,
  useDeleteTagMutation,
  useGetPopularTagsQuery,
} = tagsApi 